# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: jaewon

import datetime
import logging
import pprint
import sys

from tornado import gen
from tornado.ioloop import IOLoop

from coin.base.config import Config
from coin.exchange.base.order_gateway import OrderSide, OrderType
from coin.exchange.okex.order_gateway import OkexOrderGateway
from coin.exchange.okex.kr_rest.product import OkexProduct


class TestDriver(object):
  def __init__(self, ioloop):
    self._ioloop = ioloop
    self._og = OkexOrderGateway([], [OkexProduct.FromStr('BTC-USDT')],
                                Config.from_config_filename('okex_pilot01'))
    self._og.start(self._ioloop)
    self._ioloop.add_timeout(datetime.timedelta(seconds=5), self.print_balance)
    self._ioloop.add_timeout(datetime.timedelta(seconds=10), self.loop)

  def print_balance(self):
    if self._og.is_ready():
      print('------------------------')
      print(datetime.datetime.now())
      print('BTC', self._og.get_balance('BTC'))
      print('USDT', self._og.get_balance('USDT'))
      pprint.pprint(self._og.get_working_order())
    self._ioloop.add_timeout(datetime.timedelta(seconds=10), self.print_balance)

  @gen.coroutine
  def loop(self):
    self._og.cancel_all()
    yield gen.sleep(30)

    self._og.submit(OkexProduct.FromStr('BTC-USDT'), 11000., 0.001, OrderSide.SELL, OrderType.LIMIT)
    self._og.submit(OkexProduct.FromStr('BTC-USDT'), 5000., 0.001, OrderSide.BUY, OrderType.LIMIT)

    yield gen.sleep(20)
    self._og.cancel_all()


def main(argv):
  ioloop = IOLoop.current()
  driver = TestDriver(ioloop)
  try:
    ioloop.start()
  except KeyboardInterrupt:
    pass


if __name__ == '__main__':
  logging.basicConfig(level='DEBUG', format='%(levelname)s %(asctime)s %(name)s] %(message)s')
  sys.exit(main(sys.argv))
